from ast import Str
import os
from django.shortcuts import render
from django.core.paginator import Paginator
from django.core import serializers
# Create your views here.
# 视图层的操作函数
from django.http import HttpResponse, JsonResponse
from web_api.models import Article, EvaluationIndex
import json
import xlrd

# 测试，新增文章


def add_article(request):
    if request.method == "POST":
        req = json.loads(request.body)
        print(req)
        key_flag = req.get("title") and req.get("content") and len(req) == 2
        # 判断请求体是否正确
        if key_flag:
            title = req["title"]
            content = req["content"]
            # title返回的是一个list
            title_exist = Article.objects.filter(title=title)
            # 判断是否存在同名title
            if len(title_exist) != 0:
                return JsonResponse({"status": "BS.400", "msg": "title aleady exist,fail to publish."})

            '''插入数据'''
            add_art = Article(title=title, content=content, status="alive")
            add_art.save()
            return JsonResponse({"status": "BS.200", "msg": "publish article sucess."})
        else:
            return JsonResponse({"status": "BS.400", "message": "please check param."})

    # 查询所有文章和状态
    if request.method == "GET":
        articles = {}
        query_art = Article.objects.all()
        for title in query_art:
            articles[title.title] = title.status
        return JsonResponse({"status": "BS.200", "all_titles": articles, "msg": "query articles sucess."})

# 测试，增加记录


def add_index(request):
    if request.method == "POST":
        req = json.loads(request.body)
        print("POST index:")
        print(req)
        return JsonResponse({"status": "BS.200", "msg": "query index sucess."})

    if request.method == "GET":
        print("GET index")
        return JsonResponse({"status": "BS.200", "msg": "query index sucess."})


def check_index(request):
    if request.method == "POST":
        req = json.loads(request.body)
        print("POST index:")
        print(req)
        return JsonResponse({"status": "BS.200", "msg": "query index sucess."})

# 正式方法

# 上传


def credit_risk_input(request):
    BASE_DIR = os.getcwd()
    if request.method == "POST":
        # 数据转存
        print("POST start")
        myFile = request.FILES.get("file", None)
        if myFile:
            dir = os.path.join(BASE_DIR, 'temp')
            destination = open(os.path.join(dir, "temp"+myFile.name[myFile.name.find('.'):]),
                               'wb+')
            for chunk in myFile.chunks():
                destination.write(chunk)
            destination.close()
            BASE_DIR = os.path.join(
                dir, "temp"+myFile.name[myFile.name.find('.'):])

        # 数据写入
        readboot = xlrd.open_workbook(BASE_DIR)
        return JsonResponse({"status": "200", "msg": "post credit risk file sucess."})

# 导入评估结果


def create_risk_evlation(request):
    # 这里改一下就可以是 csv
    filename = "temp.xls"
    # 打开xls文件
    # windows
    # file_xlsx = xlrd.open_workbook(os.getcwd() + "\\temp\\" + filename)
    # linux
    file_xlsx = xlrd.open_workbook(os.getcwd() + "/temp/" + filename)
    # 获取所有sheet表
    all_sheet = file_xlsx.sheets()
    # 获取第一张表
    sheet1 = all_sheet[0]
    # sheet1_name = sheet1.name
    # 获取表的行数，同理sheet1.ncols表的列数，sheet1.name获取表的名字
    sheet1_rows = sheet1.nrows
    value_list = []
    for i in range(2, sheet1_rows-1):
        if sheet1.row_values(i):
            value_list.append(EvaluationIndex(
                name=sheet1.row_values(i)[0] if sheet1.row_values(i)[
                    0] != '' else 0,
                LR=sheet1.row_values(i)[1] if sheet1.row_values(i)[
                    1] != '' else 0,
                QR=sheet1.row_values(i)[2] if sheet1.row_values(i)[
                    2] != '' else 0,
                CR=sheet1.row_values(i)[3] if sheet1.row_values(i)[
                    3] != '' else 0,
                DNWR=sheet1.row_values(i)[4] if sheet1.row_values(i)[
                    4] != '' else 0,
                ER=sheet1.row_values(i)[5] if sheet1.row_values(i)[
                    5] != '' else 0,
                ICR=sheet1.row_values(i)[6] if sheet1.row_values(i)[
                    6] != '' else 0,
                NAIR=sheet1.row_values(i)[7] if sheet1.row_values(i)[
                    7] != '' else 0,
                NPMC=sheet1.row_values(i)[8] if sheet1.row_values(i)[
                    8] != '' else 0,
                ROA=sheet1.row_values(i)[9] if sheet1.row_values(i)[
                    9] != '' else 0,
                ROPC=sheet1.row_values(i)[10] if sheet1.row_values(i)[
                    10] != '' else 0,
                JROA=sheet1.row_values(i)[11] if sheet1.row_values(i)[
                    11] != '' else 0,
                CROE=sheet1.row_values(i)[12] if sheet1.row_values(i)[
                    12] != '' else 0,
                ROST=sheet1.row_values(i)[13] if sheet1.row_values(i)[
                    13] != '' else 0,
                TATO=sheet1.row_values(i)[14] if sheet1.row_values(i)[
                    14] != '' else 0,
                TOAR=sheet1.row_values(i)[15] if sheet1.row_values(i)[
                    15] != '' else 0,
                GRON=sheet1.row_values(i)[16] if sheet1.row_values(i)[
                    16] != '' else 0,
                IROBR=sheet1.row_values(i)[17] if sheet1.row_values(i)[
                    17] != '' else 0,
                TAGR=sheet1.row_values(i)[18] if sheet1.row_values(i)[
                    18] != '' else 0,
                GROOP=sheet1.row_values(i)[19] if sheet1.row_values(i)[
                    19] != '' else 0,
                NPGR=sheet1.row_values(i)[20] if sheet1.row_values(i)[
                    20] != '' else 0,
                index=int(sheet1.row_values(i)[21]),
                predict=sheet1.row_values(i)[22],
            ))

    EvaluationIndex.objects.bulk_create(value_list)
    return JsonResponse({"status": "200", "msg": "post credit risk file sucess."})

# 分页查询
# demo
# {
#     "page":1,
#     "pageSize":4
# }


def page_query_for_evaluation(request):
    if request.method == "POST":
        page = int(json.loads(request.body).get('page'))
        pageSize = int(json.loads(request.body).get('pageSize'))
        res = {}
        data_list = EvaluationIndex.objects.all()
        # 创建分页对象
        ptr = Paginator(data_list, pageSize)
        res['total'] = ptr.count
        datas = ptr.page(page)
        res['list'] = json.loads(serializers.serialize("json", datas))
        return JsonResponse(res)

# 同分页模糊查询
# demo
# {
#     "page":1,
#     "pageSize":5,
#     "query_name":"ST"
# }


def query_for_evaluation(request):
    if request.method == "POST":
        query_name = json.loads(
            request.body).get('query_name')
        page = int(json.loads(request.body).get('page'))
        pageSize = int(json.loads(request.body).get('pageSize'))
        res = {}
        data_list = EvaluationIndex.objects.filter(
            name__contains=query_name)  # 查询整个Master
        # 创建分页对象
        ptr = Paginator(data_list, pageSize)
        res['total'] = ptr.count
        datas = ptr.page(page-1)
        res['list'] = json.loads(serializers.serialize("json", datas))
        return JsonResponse(res)

# 重置object


def reset_evaluation(request):
    if request.method == "POST":
        EvaluationIndex.objects.all().delete()

        return JsonResponse({"status": "200", "msg": "post credit risk file sucess."})
